<?php

//  functions.php
//  Memento 3.0
//
//  Created by Christopher Burrows on 10-07-26
//  Copyright 2010 Team Memento. All rights reserved.
//
//    Description:
//  Contains various functions which are used by multiple
//  modules. Success values are always the first value outputed.
//  This should be checked to be true before any further parsing
//  is done as failure will often not continue to provide additional
//  output (e.g. session tokens).
//
//  10-07-26: File created. (C. Burrows)
//  10-07-31: xml_list added. (C. Burrows)

// Establish a connection to the server. Echoes false if the connection
// fails, or returns true if successful.
function connect_to_database()
{
    
    $host = "10.10.10.3";
    $db_name = "mementof_memento";     // database name
    $username = "mementof_user";
    $password = "memento";
    
    // Connect to server and select the database
    mysql_connect("$host", "$username", "$password") or die("0".PHP_EOL);
    mysql_select_db("$db_name") or die("0".PHP_EOL);
    
    return 1;

}

// Matches $username and $password to an entry in the
// 'users' table. If valid, then a session is created in
// the 'sessions' table with an expiry time set for one
// hour. The session token is echoed back.
//
// Output sequence:
// Line 1: Success (bool)
// Line 2: Session id (string)
function authenticate($username, $password)
{
    
    // Sanitize input
    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysql_real_escape_string($username);
    $password = mysql_real_escape_string($password);
    $username = strtolower($username);
    
    $result = mysql_query("SELECT * FROM users WHERE username='$username' 
                and password_hash='$password'");
    
    $count = mysql_num_rows($result);
    
    // If $username and $password were accepted then $count will be 1
    if($count == 1) {
      
        // Signal success and generate the session_id
        $success = 1;
        $session_id = md5(time().$username);
        
        // Prepare entry into Sessions table
        $result = mysql_query("SELECT collection_id FROM users WHERE
                    username='$username'") or die("0".PHP_EOL);
        $row = mysql_fetch_array($result);
        $collection_id = $row['collection_id'];
        $expiry_time = date( 'Y-m-d H:i:s', mktime(date("H")+1));
        
        mysql_query("INSERT INTO sessions (session_token, collection_id,
                    expiry_time) VALUES ('$session_id', $collection_id,
                    '$expiry_time')") or die("0".PHP_EOL);
      
    } else {
        
        // Authenticate failed
        $success = 0;
        $session_id = md5(-1);
        
    }
    
    echo $success.PHP_EOL;
    echo $session_id.PHP_EOL;
    
}

// Creates a new user account with the passed
// $username and $password. If the arguments are
// empty, or a user name is already taken, then
// the function fails. Afterwards, the account is
// authenticated and a session token is provided.
//
// Output:
// Line 1: Account creation success (bool)
// Line 2: Session token (string)
function create_user($username, $password)
{
    if ($username == "" or $password == "") {
        // Required fields are missing, so output false and die
        die("0".PHP_EOL);
    }
    
    $encrypted_password = md5($password);
    
    // Sanitize input
    $username = stripslashes($username);
    $encrypted_password = stripslashes($encrypted_password);
    $username = mysql_real_escape_string($username);
    $encrypted_password = mysql_real_escape_string($encrypted_password);
    $username = strtolower($username);
    
    $result = mysql_query("SELECT * FROM users WHERE username='$username'")
                or die("0".PHP_EOL);
    
    $count = mysql_num_rows($result);
    
    // If $myusername is unique, then count will be zero
    if($count != 0) {
    
        echo "0".PHP_EOL;
    
    } else {
    
        mysql_query("INSERT INTO users (username, password_hash) 
                VALUES ('$username', '$encrypted_password')") or die("0".PHP_EOL); 
        authenticate($username, $encrypted_password);
    
    }

}

// Checks if a session token has not passed its expiry
// time. If it has not, then the expiry time is incremented
// by 60 minutes.
//
// Returns: True iff session has not expired.
function validate_session_token($session_token)
{

    $result = mysql_query("SELECT * FROM sessions WHERE
            session_token='$session_token'") or die('0');
    $row = mysql_fetch_array($result);
    
    $expiry_time = strtotime($row['expiry_time']);    
    $collection_id = $row['collection_id'];
    
    // Check if it is an hour past the sessions' expiry time. If
    // so, return false; otherwise, update the expiry time and proceed.
    if (time() >= $expiry_time + 3600) {
        
        return false;
    
    } else {
        
        $expiry_time = date( 'Y-m-d H:i:s', mktime(date("H")+1));
        $result = mysql_query("UPDATE sessions SET expiry_time='$expiry_time'
                WHERE session_token='$session_token'");
        
        return true;

    }
    
}

// Outputs the metadata for a specific memory
function xml_list($collection_id, $memory_id) {

    // Collect from the memories table all entries
    // for $collection_id
    $result = mysql_query("SELECT * FROM memories WHERE
            collection_id='$collection_id' AND memory_id='$memory_id'") or die(mysql_error());
            
    $row = mysql_fetch_array($result);
    
    header('Content-Type: text/xml');
    
    $time = date("Y-m-d", $row['memory_time']).'T'.date("H:i:s", $row['memory_time']).'Z';
    
    // Construct the XML page
    echo '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
    echo '<!DOCTYPE memories PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'.PHP_EOL;
    echo '<plist version="1.0">'.PHP_EOL;
    echo '<dict>'.PHP_EOL;
    echo '<key>memoryId</key>'.PHP_EOL;
    echo '<integer>'.$row['memory_id'].'</integer>'.PHP_EOL;
    echo '<key>latitude</key>'.PHP_EOL;
    echo '<real>'.$row['latitude'].'</real>'.PHP_EOL;
    echo '<key>longitude</key>'.PHP_EOL;
    echo '<real>'.$row['longitude'].'</real>'.PHP_EOL;
    echo '<key>dateTime</key>'.PHP_EOL;
    echo '<date>'.$time.'</date>'.PHP_EOL;
    echo '</dict>'.PHP_EOL;
    echo '</plist>'.PHP_EOL;

}

?>